package com.seeyon.apps.kkEvent;

import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ModuleType;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.content.comment.Comment;
import com.seeyon.ctp.common.content.comment.CommentManager;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.common.po.comment.CtpCommentAll;
import com.seeyon.ctp.common.template.manager.TemplateManager;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.annotation.Inject;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import org.apache.commons.logging.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author wangyong
 * @date 2023/9/25 11:07
 * 关于V5处理前事件，该处理前事件现在存在提交不了，重复触发等bug，
 * 后面项目慎用，已经有多个项目反馈了，目前研发不处理该bug，可以采用超级节点
 * 或者 监听事件 做替换，后面项目经理提出用处理前做需求的提前告知他风险
 */
public class event extends AbstractWorkflowEvent {

    private final Log LOG = CtpLogFactory.getLog(event.class);
    private static final EnumManager enumManager = (EnumManager) AppContext.getBean("enumManagerNew");
    private static CAP4FormDataManager cap4FormDataManager = (CAP4FormDataManager) AppContext.getBean("cap4FormDataManager");
    private final ColManager colManager = (ColManager) AppContext.getBean("colManager");
    private final FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
    private final TemplateManager templateManager = (TemplateManager) AppContext.getBean("templateManager");
    private final OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
    private SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
    CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");

    @Inject
    private AffairManager affairManager;

    @Inject
    private CommentManager commentManager;

    @Override
    public String getId() {
        return "kkEvent";
    }

    @Override
    public String getLabel() {
        return "流程节点事件名称";
    }

    @Override
    public ApplicationCategoryEnum getAppName() {
        return ApplicationCategoryEnum.form;
    }

    /**
     * 处理前
     * @param data
     * @return
     */
    @Override
    public WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {

        return null;
    }

    /**
     * 处理后
     *
     * @param data
     */
    @Override
    public void onFinishWorkitem(WorkflowEventData data) {
        try {

            //获取summary
            ColSummary summary = colManager.getColSummaryById(data.getSummaryId());
            Long summaryId = summary.getId();
            //获取表单模板编号
            String templateCode = getTemplateCode(summary);
            if (templateCode == null) {
                return;
            }

            //获取formBean
            FormBean formBean = cap4FormManager.getFormByFormCode(templateCode);
            List<FormTableBean> formTableBeans = formBean.getSubTableBean();
            FormTableBean formSubTableBean = formTableBeans.get(0);
            String tableSubName = formSubTableBean.getTableName();

            //获取主表数据
            FormDataMasterBean formDataMasterBean = formApi4Cap4.findDataById(summary.getFormRecordid(), formBean, null);
            List<FormTableBean> subTableBean = formBean.getSubTableBean();
            List<FormDataSubBean> ysdsubData = formDataMasterBean.getSubData(tableSubName);

            // 获取发起人
            long dataAffairId = data.getAffairId();
            CtpAffair dataAffairend = affairManager.get(dataAffairId);
            Long senderId = dataAffairend.getSenderId();
            OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
            V3xOrgMember datanodeName = orgManager.getMemberById(senderId);
            List<Comment> commentList = commentManager.getCommentAllByModuleId(ModuleType.collaboration, summaryId);
            CtpCommentAll drfatComment = commentManager.getDrfatComment(summaryId);

            List<Map<String, Object>> subListData = new ArrayList<Map<String, Object>>();
            for (Comment comment : commentList) {
                Map<String, Object> subTempData = new HashMap<>();
                //获取节点审批人
                Long createId = comment.getCreateId();
                // String LoginName = orgManager.getMemberById(createId).getLoginName();
                String LoginName = orgManager.getMemberById(createId).getCode();
                String createName = comment.getCreateName();
                //获取审批人所在部门
                String departmentFullName = comment.getDepartmentName();
                //获取审批时间
                Date createDate = comment.getCreateDate();
                String formattedDates = formatDate(createDate);
                // 获取处理人态度
                String attr4 = comment.getExtAtt4();
                Map<String, Object> attrMap = new HashMap<String, Object>();
                if ("haveRead".equals(attr4)) {
                    attr4 = "已阅";
                } else if ("agree".equals(attr4)) {
                    attr4 = "同意";
                } else if ("disagree".equals(attr4)) {
                    attr4 = "不同意";
                } else {
                    attr4 = "";
                }
                //获取处理人审批意见
                String content = comment.getContent();

                // 获取节点名称
                Long affairIds = comment.getAffairId();
                CtpAffair affair = affairManager.get(affairIds);
                String nodeName = affair.getNodeName();
            }
        }catch(Exception e){
            LOG.error("【onFinishWorkitem】-----e=" + e);
        }
    }

    /**
     * 回退前
     *
     * @param data
     * @return
     */
    @Override
    public WorkflowEventResult onBeforeStepBack(WorkflowEventData data) {

        return null;
    }

    /**
     * 回退后
     *
     * @param data
     */
    @Override
    public void onStepBack(WorkflowEventData data) {

    }

    /**
     * 取回前
     *
     * @param data
     * @return
     */
    @Override
    public WorkflowEventResult onBeforeTakeBack(WorkflowEventData data) {

        return null;
    }

    /**
     * 取回后
     *
     * @param data
     */
    @Override
    public void onTakeBack(WorkflowEventData data) {

    }

    /**
     * 撤销前
     *
     * @param data
     * @return
     */
    @Override
    public WorkflowEventResult onBeforeCancel(WorkflowEventData data) {

        return null;
    }

    /**
     * 撤销后
     */
    @Override
    public void onCancel(WorkflowEventData data) {

    }

    /**
     * 终止前
     *
     * @param data
     * @return
     */
    @Override
    public WorkflowEventResult onBeforeStop(WorkflowEventData data) {

        return null;
    }

    /**
     * 终止后
     *
     * @param data
     */
    @Override
    public void onStop(WorkflowEventData data) {

    }

    /**
     * 流程发起前
     *
     * @param data
     * @return
     */
    @Override
    public WorkflowEventResult onBeforeStart(WorkflowEventData data) {

        return null;
    }

    /**
     * 流程发起后
     *
     * @param data
     */
    @Override
    public void onStart(WorkflowEventData data) {

    }

    /**
     * 流程结束前
     *
     * @param data
     * @return
     */
    @Override
    public WorkflowEventResult onBeforeProcessFinished(WorkflowEventData data) {

        return null;
    }

    /**
     * 流程结束后
     *
     * @param data
     */
    @Override
    public void onProcessFinished(WorkflowEventData data) {

    }

    /**
     * 获取表单提交地址
     * @param summary
     * @return
     */
    private String getTemplateCode(ColSummary summary) {
        String templateCode = null;
        try {
            templateCode = templateManager.getCtpTemplate(summary.getTempleteId()).getTempleteNumber();
        } catch (BusinessException e) {
            LOG.error("kkTAMPOrgDataSyncEvent------获取流程模板编号失败", e);
        }
        if (templateCode == null || templateCode.isEmpty()) {
            LOG.error("kkTAMPOrgDataSyncEvent------流程模板编号为空");
            return null;
        }
        LOG.info("kkTAMPOrgDataSyncEvent------流程模板编号：" + templateCode);
        return templateCode;
    }

    // 时间转换
    public static String formatDate(Object dateOrTime) {
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 输出格式为 yyyy-MM-dd HH:mm:ss
        String[] inputFormats = {
                "yyyy-MM-dd HH:mm:ss",
                "yyyy-MM-dd HH:mm",
                "yyyy-MM-dd",
                "MM/dd/yyyy HH:mm:ss",
                "MM/dd/yyyy"
        }; // 支持的输入格式

        if (dateOrTime instanceof Date) {
            // 如果是 Date 类型，直接格式化
            return outputFormat.format((Date) dateOrTime);
        } else if (dateOrTime instanceof String) {
            // 如果是 String 类型，尝试用多种格式解析
            for (String format : inputFormats) {
                SimpleDateFormat inputFormat = new SimpleDateFormat(format);
                try {
                    Date parsedDate = inputFormat.parse((String) dateOrTime);
                    return outputFormat.format(parsedDate); // 成功解析后格式化为目标格式
                } catch (ParseException e) {
                    // 忽略当前格式的解析失败，继续尝试下一个格式
                }
            }
            // 如果所有格式都无法解析，抛出异常或返回错误提示
            throw new IllegalArgumentException("无法解析输入的日期字符串：" + dateOrTime);
        } else {
            throw new IllegalArgumentException("输入类型不支持。必须是 Date 或 String。");
        }
    }
}
